package cn.learn.config;

import cn.learn.properties.LoginResponseType;
import cn.learn.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 失败处理器，也可以实现AuthenticationFailureHandler，
 * 理由跟成功处理器一样
 *
 * @author huangyezhan
 * @date 2020年02月14日22:46
 */
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private static final Logger logger = LoggerFactory.getLogger(MyAuthenticationFailureHandler.class);

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SecurityProperties securityProperties;


    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {
        //填写自己的业务逻辑

        if (exception instanceof BadCredentialsException) {
        }
        logger.info("登录失败的用户账号[{}]，失败原因：{} -> {}。", request.getParameter("username"), exception.getClass().getName(), exception.getMessage());
        logger.info("登录失败的用户账号ip：[{}]，该应用所在服务器：[{}]。", request.getRemoteAddr(), request.getLocalAddr());
        logger.info("失败记录：", exception);

        //响应方式：json或者redirect
        if (LoginResponseType.JSON.equals(securityProperties.getLoginType())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");

            //定义返回内容
            Map<String ,String> map = new HashMap<>(16);
            map.put("msg",exception.getMessage());
            map.put("ExceptionClassName",exception.getClass().getName());
            response.getWriter().write(objectMapper.writeValueAsString(map));
        }else {
            super.onAuthenticationFailure(request, response, exception);
        }

    }


}
